package top.datacluster.basic.algorithm.leetcode.heap;

import top.datacluster.basic.algorithm.leetcode.link.ListNode;

import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * 23. 合并K个排序链表
 * 合并 k 个排序链表，返回合并后的排序链表。请分析和描述算法的复杂度。
 *
 * 示例:
 *
 * 输入:
 * [
 *   1->4->5,
 *   1->3->4,
 *   2->6
 * ]
 * 输出: 1->1->2->3->4->4->5->6
 */
public class LeetCode23 {

    public ListNode mergeKLists(ListNode[] lists) {
        Comparator<ListNode> comparator = new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return Integer.compare(o1.val, o2.val);
            }
        };

        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, comparator);
        for (int i = 0; i < lists.length; i++){
            if (lists[i] != null){
                queue.offer(lists[i]);
                lists[i] = lists[i].next;
            }
        }

        ListNode head = new ListNode(0);
        ListNode index = head;
        while (!queue.isEmpty()){
            ListNode temp = queue.poll();
            index.next = temp;
            index = index.next;
            if (temp.next != null){
                queue.offer(temp.next);
            }
        }

        return head.next;
    }
}
